package com.example.roleplay.controller;

import com.example.roleplay.domain.KnowledgeSnippet;
import com.example.roleplay.domain.Persona;
import com.example.roleplay.domain.SessionMemory;
import com.example.roleplay.domain.Skill;
import com.example.roleplay.dto.SessionCreateRequest;
import com.example.roleplay.dto.SessionCreateResponse;
import com.example.roleplay.service.PersonaService;
import com.example.roleplay.service.SessionService;
import com.example.roleplay.service.KnowledgeService;
import com.example.roleplay.service.AIEnhancementService;
import com.example.roleplay.service.llm.LLMClient;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 文本聊天REST API控制器
 * 提供简单的HTTP接口进行文本对话
 */
@Slf4j
@RestController
@RequestMapping("/api/chat")
@RequiredArgsConstructor
public class TextChatController {

    private final SessionService sessionService;
    private final PersonaService personaService;
    private final LLMClient llmClient;
    private final KnowledgeService knowledgeService;
    private final AIEnhancementService aiEnhancementService;

    /**
     * 发送文本消息并获取回复
     */
    @PostMapping("/send")
    public ResponseEntity<Map<String, Object>> sendMessage(@RequestBody Map<String, Object> request) {
        try {
            String message = (String) request.get("message");
            String personaId = (String) request.get("personaId");
            String sessionId = (String) request.get("sessionId");

            if (message == null || message.trim().isEmpty()) {
                return ResponseEntity.badRequest().body(Map.of("error", "消息内容不能为空"));
            }

            if (personaId == null || personaId.trim().isEmpty()) {
                return ResponseEntity.badRequest().body(Map.of("error", "角色ID不能为空"));
            }

            // 验证角色是否存在
            Persona persona = personaService.getPersonaById(personaId);
            if (persona == null) {
                return ResponseEntity.badRequest().body(Map.of("error", "指定的角色不存在"));
            }

            // 如果没有会话ID或会话无效，创建新会话
            if (sessionId == null || sessionId.trim().isEmpty() || !sessionService.isSessionValid(sessionId)) {
                sessionId = UUID.randomUUID().toString();
                
                SessionCreateRequest createRequest = SessionCreateRequest.builder()
                        .personaId(personaId)
                        .preferredLanguage("zh-CN")
                        .build();
                
                SessionCreateResponse sessionResponse = sessionService.createSession(createRequest);
                sessionId = sessionResponse.getSessionId();
                
                log.info("创建新的文本聊天会话: {}, 角色: {}", sessionId, personaId);
            }

            // 更新会话活动时间
            sessionService.updateSessionActivity(sessionId);

            // 获取会话记忆和角色信息
            SessionMemory sessionMemory = sessionService.getSessionMemory(sessionId);
            if (sessionMemory == null) {
                return ResponseEntity.internalServerError().body(Map.of("error", "会话记忆获取失败"));
            }

            // 知识增强（如果角色支持引用技能）
            List<String> enhancedContexts = List.of();
            if (persona.getSkills().contains(Skill.CITATION)) {
                try {
                    enhancedContexts = aiEnhancementService.getEnhancedContext(message, 3);
                    log.debug("知识增强完成 - 会话: {}, 相关片段数: {}", sessionId, enhancedContexts.size());
                } catch (Exception e) {
                    log.warn("知识增强失败，继续正常对话: {}", e.getMessage());
                }
            }

            // 获取LLM响应（同步方式）
            String response = llmClient.chat(personaId, sessionId, message, enhancedContexts);

            // 更新会话记忆
            sessionService.updateSessionMemory(sessionId, message, response, 
                    SessionMemory.MessageType.TEXT, List.of(Skill.MEMORY));

            // 构建响应
            Map<String, Object> result = Map.of(
                    "sessionId", sessionId,
                    "response", response,
                    "personaId", personaId,
                    "personaName", persona.getName(),
                    "timestamp", System.currentTimeMillis()
            );

            log.info("文本聊天响应完成 - 会话: {}, 角色: {}, 消息长度: {}", 
                    sessionId, personaId, response.length());

            return ResponseEntity.ok(result);

        } catch (Exception e) {
            log.error("文本聊天处理失败", e);
            return ResponseEntity.internalServerError().body(Map.of("error", "处理失败: " + e.getMessage()));
        }
    }

    /**
     * 获取会话历史
     */
    @GetMapping("/history/{sessionId}")
    public ResponseEntity<Map<String, Object>> getSessionHistory(@PathVariable String sessionId) {
        try {
            if (!sessionService.isSessionValid(sessionId)) {
                return ResponseEntity.notFound().build();
            }

            SessionMemory sessionMemory = sessionService.getSessionMemory(sessionId);
            if (sessionMemory == null) {
                return ResponseEntity.notFound().build();
            }

            Map<String, Object> result = Map.of(
                    "sessionId", sessionId,
                    "personaId", sessionMemory.getPersonaId(),
                    "messages", sessionMemory.getConversationHistory(),
                    "createdAt", sessionMemory.getCreatedAt(),
                    "lastActiveAt", sessionMemory.getLastActiveAt()
            );

            return ResponseEntity.ok(result);

        } catch (Exception e) {
            log.error("获取会话历史失败", e);
            return ResponseEntity.internalServerError().body(Map.of("error", "获取历史失败: " + e.getMessage()));
        }
    }

    /**
     * 清空会话记忆
     */
    @DeleteMapping("/history/{sessionId}")
    public ResponseEntity<Map<String, Object>> clearSessionHistory(@PathVariable String sessionId) {
        try {
            if (!sessionService.isSessionValid(sessionId)) {
                return ResponseEntity.notFound().build();
            }

            sessionService.clearSessionMemory(sessionId);
            
            Map<String, Object> result = Map.of(
                    "sessionId", sessionId,
                    "message", "会话记忆已清空"
            );

            return ResponseEntity.ok(result);

        } catch (Exception e) {
            log.error("清空会话记忆失败", e);
            return ResponseEntity.internalServerError().body(Map.of("error", "清空失败: " + e.getMessage()));
        }
    }
}